<?php

class ImageService extends AbstractService
{

    protected function _init()
    {
	$this->setMapper(new ImageMapper());
    }

    public function getByReview(ReviewModel $model)
    {
	if (!$model->getId()) {
	    return false;
	}

	$cacheSlot = new CacheSlotsReviewFeatures($model, 'images');
	if (($images = $cacheSlot->load()) === false) {
	    $images = $this->getMapper()->getAllFeatures($model->getId(), REVIEW_TABLE, IMAGE_TABLE);
	    if (!$images) {
		$images = array();
	    }
	    $cacheSlot->setData($images)->save();
	}

	if ($images) {
	    $model->setImages($images);
	}
    }

    public function getByOpinion(OpinionModel $model)
    {
	if (!$model->getId()) {
	    return false;
	}

	$cacheSlot = new CacheSlotsOpinionFeatures($model, 'images');
	if (($images = $cacheSlot->load()) === false) {
	    $images = $this->getMapper()->getAllFeatures($model->getId(), OPINION_TABLE, IMAGE_TABLE);
	    $cacheSlot->setData($images)->save();
	}

	if ($images) {
	    $model->setImages($images);
	}
    }

    public static function getThumbName($min, $max)
    {
	$str = '';
	$a = rand($min, $max);
	while ($a > 0) {
	    if (rand(0, 9) >= 5) {
		$str .= rand(0, 9);
	    }
	    else {
		$str .= chr(rand(97, 122));
	    }
	    $a -= 1;
	}
	return $str;
    }

    public function remove(AbstractModel $model)
    {
	if (parent::remove($model)) {
	    return $this->removeLocalImage($model);
	}
	return false;
    }

    public function removeRelations($id)
    {
	if (!$id) {
	    return false;
	}
	$this->getMapper()->removeRelations($id);
    }

    public function onBeforeRemove(AbstractModel $model)
    {
	if ($model->getId()) {
	    $this->removeRelations($model->getId());
	}
	return parent::onBeforeRemove($model);
    }

    public function removeLocalImage(ImageModel $model)
    {
	if ($model->getId() && $model->path) {
	    $origin = $model->getImagePath(false, true);
	    $thumb = $model->getImagePath(true, true);
	    try {
		if (file_exists($origin)) {
		    unlink($origin);
		}
		if (file_exists($thumb)) {
		    unlink($thumb);
		}
	    }
	    catch (Exception $e) {
		return false;
	    }
	}
	return true;
    }

}